from flask import Flask, request, jsonify
import logging
from datetime import datetime
import json
import pymysql

def create_connection():
    # MySQL数据库连接配置
    db_config = {
        'host': '121.43.234.11',  # 数据库服务器IP地址
        'port': 3306,  # 端口号
        'user': 'himalaya',  # 用户名
        'password': 'E8h3DkdKYj7e82kw',  # 密码
        'database': 'himalaya',  # 数据库名
        'charset': 'utf8mb4'  # 字符集
    }

    try:
        conn = pymysql.connect(**db_config)
        return conn
    except Exception as e:
        logging.error(f"数据库连接失败: {e}")
        return None





# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('api.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)

app = Flask(__name__)

# 示例数据存储
users = {
    '1': {'name': '张三', 'age': 25},
    '2': {'name': '李四', 'age': 30}
}


def query_target_data(conn,account_id):
    cursor = conn.cursor()
    sql = f"select * from bsky_msg_task where target_account = '{account_id}' and msg_status = 0"
    cursor.execute(sql)
    return cursor.fetchall()

@app.route('/api/get_content/<account_id>', methods=['GET'])
def get_content(account_id):
    """获取指定账户的 需要发布的信息"""
    logging.info(f"account_id : {account_id}")

    db_conn = create_connection()

    data_size = query_target_data(db_conn,account_id)
    cursor = db_conn.cursor()
    # print(data_size)
    try:
        for row in data_size:
            update_sql = f"update bsky_msg_task set msg_status = 1 where id = {row[0]}"
            cursor.execute(update_sql)
        db_conn.commit()
    finally:
        cursor.close()
        db_conn.close()
    return jsonify(data_size)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)